from twisted.words.protocols import jabber 
from twisted.words.protocols.jabber import client,jid
from twisted.words.xish import domish
from twisted.words.xish import xpath
from twisted.internet import reactor

class JabberClient(object):

    def messageHandler(self, el):
        for node in el.children:
            if node.name == "body":
                self.current_message = str(node)

    def authd(self, xmlstream):
        self.xmlstream = xmlstream
        print "we've authd!"

        #need to send presence so clients know we're
        #actually online
        presence = domish.Element(('jabber:client','presence'))
        xmlstream.send(presence)
        xmlstream.addObserver('/message', self.messageHandler)

    def send(self, to, msg):
        message = domish.Element(('jabber:client', 'message'))
        message["to"] = to.split("xmpp:")[-1]
        message["from"] = self.jid.full()
        message["id"] = "foo"
        message["type"] = "chat"
        message.addElement("body", "jabber:client", msg)
        
        self.xmlstream.send(message)

    def invaliduserEvent(self, xmlstream):
        print 'baduser'

    def authfailedEvent(self, xmlstream):
        print 'authfailed'

    def __init__(self):
        self.jid = jid.JID('tvachon@jabber.org/bot')
        factory = client.basicClientFactory(self.jid, "wiccan01")
        factory.addBootstrap('//event/stream/authd',self.authd)
        factory.addBootstrap('//event/client/basicauth/invaliduser', self.invaliduserEvent)
        factory.addBootstrap('//event/client/basicauth/authfailed',  self.authfailedEvent)
        reactor.connectTCP('jabber.org',5222,factory)

jabber_client = JabberClient()


from twisted.web2 import server, http, resource, channel, stream


class Sender(resource.Resource):
    def http_PUT(self, request):
        def handleData(data):
            # process data
            pass
        def finished(self, result, request):
            jabber_client.send("travis.vachon@gmail.com", result)
        return http.Response("sent")

        def failed(self, reason, request):
            return http.Response(reason)

        d = stream.readStream(request.stream, handleData)
        d.addCallbacks(finished, failed, 
                       callbackArgs=(request,),
                       errbackArgs=(request,)
        )
        d.addErrback(failed, request)
        return d
    
class Toplevel(resource.Resource):
    addSlash = True
    child_send = Sender()
    def render(self, ctx):
        return http.Response(stream=jabber_client.current_message)

    
site = server.Site(Toplevel())

reactor.listenTCP(8181, channel.HTTPFactory(site))





reactor.run()